#!/usr/bin/env python
# coding: utf-8

# In[1]:


import pandas as pd
import numpy as np
from pandas import Series,DataFrame 


# In[24]:


num = [1,2,3,4]
new = num.copy()
#re =num*new
print (new)


# In[30]:


num = [1,2,3,4,5]
new = []
for i in num:
    new.append(i**2)


# # 随机练习-1

# In[44]:


import random
import string
a = random.uniform(0,10)#范围内生成随机浮点数，参数a b 大小关系不受限制
b = random.randint(11,20)#随机整数，参数a 必须大于 b
c = random.randrange(0,101) #随机偶数
d = random.choice("qweasdzxc") #随机字符
e = random.sample("uiojklnm,",3) #随机 指定数量 字符
items = [1,2,3,4,5,6]
random.shuffle(items) #洗牌，随机排序

f = random.sample(['a','b','c','d','e','f','g','h','i','j'], 3)

st =""
g = st.join(f)

#string.join(random.sample(['a','b','c','d','e','f','g','h','i','j'], 3)).replace(" ","")  ??

print (g)
print (f)
#print (st)
print (items)
print (e)
print (d)
print (c)
print (b)
print (a)


# In[115]:


def dicmake(**kwargs):

    return kwargs


# # 50种常用的matplotlib可视化-知乎

# In[8]:


import pandas as pd
import numpy as np
df = pd.read_csv("https://raw.githubusercontent.com/selva86/datasets/master/midwest_filter.csv")


# In[20]:


#df.info()
#df.describe()
#df.shape
print (df)


# In[2]:


import matplotlib as mpl
import matplotlib.pyplot as plt
import seaborn as sns
import warnings; warnings.filterwarnings(action='once')

large = 22; med = 16; small = 12
params = {'axes.titlesize': large,
          'legend.fontsize': med,
          'figure.figsize': (16, 10),
          'axes.labelsize': med,
          'axes.titlesize': med,
          'xtick.labelsize': med,
          'ytick.labelsize': med,
          'figure.titlesize': large}
plt.rcParams.update(params)
plt.style.use('seaborn-whitegrid')
sns.set_style("white")
get_ipython().run_line_magic('matplotlib', 'inline')

# Version
print(mpl.__version__)  #> 3.0.0
print(sns.__version__)  #> 0.9.0


# In[13]:


midwest = pd.read_csv("https://raw.githubusercontent.com/selva86/datasets/master/midwest_filter.csv")
categories = np.unique(midwest['category'])
colors = [plt.cm.tab10(i/float(len(categories)-1)) 
          # loat 浮点数   
          # matplotlib.cm是matplotlib库中内置的色彩映射函数,tab10是颜色映射列表中的一种 色彩名
          # matplotlib.cm.[色彩]('[数据集]')即对[数据集]应用[色彩]
          for i in range(len(categories))] # range建立整数列表


# ## 实验，理解代码意思
# 
# #print(len(categories))
# for i in range(len(categories)): 
#     print (i)
#     print(categories[i])
# a = float(len(categories)-1)
# i = i in range(len(categories))
# b = i/float(len(categories)-1)
# print (a)
# print (b)
# 
# 

# ## 实验，理解代码意思
# print (colors)
# 
# 
# print (plt.cm.tab10(0))
# print ("0.5:   {}".format(( plt.cm.tab10(0.5))))
# print (plt.cm.tab10(1))
# print (plt.cm.tab10(2))
# print (plt.cm.tab10(3))
# print (plt.cm.tab10(4))
# print (plt.cm.tab10(5))
# print (plt.cm.tab10(6))
# print ("6.5:   {}".format(( plt.cm.tab10(6.5))))
# print ("7:     {}".format(( plt.cm.tab10(7))))
# print ("7.5:   {}".format(( plt.cm.tab10(7.5))))
# print ("8:     {}".format(( plt.cm.tab10(8))))
# print ("8.5:   {}".format(( plt.cm.tab10(8.5))))
# print (plt.cm.tab10(9))
# print (plt.cm.tab10(10))
# print (plt.cm.tab10(11))

# ## 实验，理解代码意思
# '''
# import matplotlib.cm
# print(matplotlib.cm.cmap_d.keys())
# a = matplotlib.cm.cmap_d.keys()
# print (len(a))
# '''
# 
# for category in enumerate(categories)
# col1 = midwest.category()
# data1 = midwest.loc[midwest.category==category, :]

# ##  问题
# 1、为什么选择 tab10 颜色集？
# 2、颜色是如何选择的？
# 

# In[ ]:





# In[36]:


# Draw Plot for Each Category
plt.figure(figsize=(16,10),dpi = 80,facecolor = 'w',edgecolor ='k')
for i,category in enumerate(categories): # i=0-13  category = AAR AAU AHR ...(14个)
    # enumerate() 函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列，同时列出数据和数据下标，一般用在 for 循环当中。
    plt.scatter('area','poptotal', # 需要的 数据列
               data = midwest.loc[midwest.category==category, :], #loc[行，列] 冒号表示取所有的列： area poptotal 这两列
               s=20, 
                cmap=colors[i], # 颜色选择
                label=str(category)) # label 标签

    # Decorations 装饰
plt.gca().set(xlim=(0.0,0.1),ylim=(0,90000),
              xlabel='Area',ylabel='Population')

plt.xticks(fontsize=12); plt.yticks(fontsize=12)
plt.title("Scatterplot of Midwest Area vs Population", fontsize=22)
plt.legend(fontsize=12)    # 说明 标签label
plt.show() 


# ## 实验，理解代码意思
# for category in enumerate(categories)
# col1 = midwest.category()
# data1 = midwest.loc[midwest.category==category, :]

# In[22]:


# Using Colormaps to set color of line in matplotlib
# https://stackoverflow.com/questions/8931268/using-colormaps-to-set-color-of-line-in-matplotlib
import matplotlib.pyplot as plt
import matplotlib.colors as colors
import matplotlib.cm as cmx
import numpy as np

fig = plt.figure()
ax = fig.add_subplot(111)
jet = colors.Colormap('jet')
cNorm  = colors.Normalize(vmin=0, vmax=values[-1])
scalarMap = cmx.ScalarMappable(norm=cNorm, cmap=jet)
lines = []
for idx in range(len(curves)):
    line = curves[idx]
    colorVal = scalarMap.to_rgba(values[idx])
    retLine, = ax.plot(line, color=colorVal)
    #retLine.set_color()
    lines.append(retLine)
ax.legend(lines, labels, loc='upper right')
ax.grid()
plt.show()


# In[24]:


# 上面问题的可行代码
import matplotlib.pyplot as plt
import matplotlib.colors as colors
import matplotlib.cm as cmx
import numpy as np

# define some random data that emulates your indeded code:
NCURVES = 10
np.random.seed(101)
curves = [np.random.random(20) for i in range(NCURVES)]
values = range(NCURVES)

fig = plt.figure()
ax = fig.add_subplot(111)
# replace the next line 
#jet = colors.Colormap('jet')
# with
jet = cm = plt.get_cmap('jet') 
cNorm  = colors.Normalize(vmin=0, vmax=values[-1])
scalarMap = cmx.ScalarMappable(norm=cNorm, cmap=jet)
print (scalarMap.get_clim())

lines = []
for idx in range(len(curves)):
    line = curves[idx]
    colorVal = scalarMap.to_rgba(values[idx])
    colorText = (
        'color: (%4.2f,%4.2f,%4.2f)'%(colorVal[0],colorVal[1],colorVal[2])
        )
    retLine, = ax.plot(line,
                       color=colorVal,
                       label=colorText)
    lines.append(retLine)
#added this to get the legend to work
handles,labels = ax.get_legend_handles_labels()
ax.legend(handles, labels, loc='upper right')
ax.grid()
plt.show()


# In[21]:


#python中的颜色相关的定义在matplotlib模块中，为方便使用，这里给大家展示一下在这个模块中都定义了哪些选颜色。
#https://blog.csdn.net/guduruyu/article/details/77836173
import matplotlib
for name, hex in matplotlib.colors.cnames.items():
    print (name,   hex)


# In[ ]:


def power(x,n):
    s = 1
    while n > 0:
        n = n +1
        s = s * n
    return s
#x = input ('输入x:')
#n = input ('输入n:')
print (power(5,5))


# In[6]:


def my_abs(x):
    if not isinstance(x, (int, float)):
        raise TypeError('bad operand type')
    if x >= 0:
        return x
    else:
        return -x
    


# In[1]:


# 斐波那契数列
def fibonacci(i):
    num_list = [0,1]
    if i < 2:
        return num_list[i]
    elif i >= 2:
        return (fibonacci(i - 2)+ fibonacci(i - 1))

print (fibonacci(10))


# In[2]:


def application(environ, start_response):
    start_response('200 OK', [('Content-Type', 'text/html')])
    body = '<h1>Hello, %s!</h1>' % (environ['PATH_INFO'][1:] or 'web')
    return [body.encode('utf-8')]


# # 30个常用python实现-简书

# In[10]:


#def fac():
num = int(input("请输入一个数字："))
factorial = 1 
    
if num < 0:
    print ("负数没有阶乘")
elif num == 0:
    print ("0的阶乘为 1 ")
else:
    for i in range (1,num +1):
         factorial = factorial * i
         print ("%d 的阶乘为 %d" % (i,factorial))
         print ("{}的阶乘为{}".format(num,factorial))


# In[6]:


def fac ():
num = int(input("请输入正整数"))
if num < 0:
   print ("负数无阶乘")
elif num == 0:
   print ("0 的阶乘等于 1")
else:
   #print (num * (num - 1))
   return num * (num - 1)


# In[3]:


def factorial(n):
    if n == 0:
        return 1
    else:
        return n * factorial(n - 1)

factorial (5)


# # 《算法图解》-- 二分法

# In[5]:


def binary_search(list,item):
    low = 0
    high = len(list) - 1
    while low <= high:
        mid = int((low + high)/2)  # 若不加 int ，则mid可能会出现浮点数，list列表不能是浮点数
        #mid = (low + high)/2
        guess = list[mid]
        if guess == item:
            return mid
        if guess < item:
            low = mid + 1
        else:
            high = mid - 1
    return


# In[14]:


#Mylist = list(range(7))  # range() 函数返回的结果是一个整数序列的对象，而不是列表。
print (Mylist)
print (len(Mylist))
Mylist = [1,3,5,7,9] 
a = binary_search(Mylist,7)
print (a)


# # iterrows 对DataFrame进行遍历
# ---
# https://blog.csdn.net/Softdiamonds/article/details/80218777

# In[2]:


import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randn(10, 4), columns=list('ABCD'))
df


# In[3]:


for i,r in df.iterrows():
    print(i,r)


# # Python-100-Days --github

# In[1]:


f = float(input('请输入华氏温度: '))
c = (f - 32) / 1.8
print('%.1f华氏度 = %.1f摄氏度' % (f, c))


# In[2]:


my_series2 = pd.Series([1,1.2,True,'MyName'])
print(my_series2)


# In[ ]:





# In[3]:


import pandas as pd
my_series1 = pd.Series({'a':'非本科程序员','b':'公号'})
print(my_series1)


# #  groupby--csdn
# ---
# python/pandas数据挖掘（十四）-groupby,聚合，分组级运算
# https://blog.csdn.net/youngbit007/article/details/54288603/

# In[2]:


import pandas as pd
import numpy as np
df = pd.DataFrame({'key1':list('aabba'),
                  'key2': ['one','two','one','two','one'],
                  'data1': np.random.randn(5),
                  'data2': np.random.randn(5)})


# In[3]:


df


# In[4]:


grouped = df['data1'].groupby(df['key1'])


# In[5]:


grouped.mean()


# In[6]:


states=np.array(['Ohio','California','California','Ohio','Ohio'])
years=np.array([2005,2005,2006,2005,2006])
df['data1'].groupby([states,years]).mean()


# In[7]:


df.groupby('key1').mean()


# ##  对分组进行迭代

# In[12]:


for name, group in df.groupby('key1'):
    print (name)
    print (group)


# In[18]:


for (k1,k2),group in df.groupby(['key1','key2']):
    '''print ('===k1,k2:')
    print (k1,k2)
    print ('===k3:')'''
    print (group)


# In[21]:


piece = dict(list(df.groupby('key1')))


# In[23]:


piece


# In[24]:


piece ['a']


# In[32]:


piece.items()


# In[33]:


piece.values()


# In[34]:


piece.keys()


# groupby默认是在axis=0上进行分组的，通过设置也可以在其他任何轴上进行分组.

# In[35]:


grouped = df.groupby(df.dtypes,axis=1)


# In[40]:


a = dict(list(grouped))
print (a)


# In[41]:


a.keys()


# ##  选取一个或者一组列

# In[ ]:


'''
df.groupby('key1')['data1']
df.groupby('key1')[['data2']]

语法糖：
df['data1'].groupby(df['key1'])
df[['data2']].groupby(df['key2'])
'''


# In[50]:


b = df.groupby(['key1','key2'])[['data2']].mean()


# In[52]:


b


# In[56]:


b.index() # 'MultiIndex' object is not callable


# In[57]:


c = df.groupby(['key1','key2'])['data2'].mean()


# In[58]:


c


# In[55]:


c.index() # 'MultiIndex' object is not callable


# ##  通过字典或者series进行分组

# In[70]:


people = pd.DataFrame(np.random.randn(5,5),
                     columns = list('abcde'),
                     index = ['Joe','Steve','Wes','Jim','Travis'])


# In[72]:


#people.ix[2:3,['b','c']] = np.nan
'''D:\Python\Anaconda\lib\site-packages\ipykernel_launcher.py:1: DeprecationWarning: 
.ix is deprecated. Please use
.loc for label based indexing or
.iloc for positional indexing

See the documentation here:
http://pandas.pydata.org/pandas-docs/stable/indexing.html#ix-indexer-is-deprecated
  """Entry point for launching an IPython kernel.
  '''


# ###  嵌套列表

# In[74]:


people.iloc[2:3,[1,2]]=np.nan  


# In[75]:


people


# In[76]:


mapping={'a':'red','b':'red','c':'blue','d':'blue','e':'red','f':'orange'}

by_column=people.groupby(mapping,axis=1)

by_column.sum()


# In[77]:


by_column=people.groupby(mapping) # 没有加 axis =1

by_column.sum()


# In[82]:


map_series = pd.Series(mapping)
map_series


# In[85]:


people.groupby(map_series,axis=1).count()


# ##  通过函数进行分组
# ---
# 相较于dic或者Series，python函数在定义分组关系映射时更有创意。任何被当做分组键的函数都会在各个索引上被调用一次，其返回值就会被用作分组名称。

# 假设你按人名的长度进行分组，仅仅传入len即可

# In[87]:


people.groupby(len).sum()


# 将函数和数组、列表、字典、Series混合使用也不是问题，因为任何东西都会最终转换为数组

# In[88]:


key_list=['one','one','one','two','two']
people.groupby([len,key_list]).sum()


# In[89]:


columns = pd.MultiIndex.from_arrays([['US','US','US','JP','JP'],[1,3,5,1,3]],names=['cty','tenor'])
hier_df = pd.DataFrame(np.random.randn(4,5),columns=columns)
hier_df


# In[92]:


hier_df.groupby(level='cty',axis=1).count()


# ##  数据聚合

# In[95]:


def peak_to_peak(arr):
    return arr.max()-arr.min()


# In[96]:


grouped.agg(peak_to_peak)


# ##  未完，待续

# # 冰雹猜想 Collatz
# 一个自然数x，如果是奇数就乘以3再加1，如果是偶数就析出偶数因数2ⁿ，这样经过若干个次数，最终回到1。

# In[2]:


# https://github.com/TheAlgorithms/Python/blob/master/maths/3n%2B1.py


from typing import Tuple, List

def n31(a: int) -> Tuple[List[int], int]: 
    """
    Returns the Collatz sequence and its length of any postiver integer. 
    >>> n31(4)
    ([4, 2, 1], 3)
    """

    if not isinstance(a, int):
        raise TypeError('Must be int, not {0}'.format(type(a).__name__))
    if a < 1: 
        raise ValueError('Given integer must be greater than 1, not {0}'.format(a))
    
    path = [a]
    while a != 1:
        if a % 2 == 0:
            a = a // 2
        else:
            a = 3*a +1
        path += [a]
    return path, len(path)

def main():
    num = 6

    path , length = n31(num)
    print("The Collatz sequence of {0} took {1} steps. \nPath: {2}".format(num,length, path))

if __name__ == '__main__':
    main()


# # 《python编程：从入门到实践》
# ---
# 9.1 创建和使用类

# In[144]:


class Restaurant():
    def __init__(self,restaurant_name,cuisine_type):
        self.restaurant_name = restaurant_name
        self.cuisine_type = cuisine_type
    def describe_restaurant(self):
        print('The restaurant\'s name is {}'.format(self.restaurant_name))
        print('The restaurant\'s cuisine is {}'.format(self.cuisine_type))
    def open_restaurant(self):
        print('The restaurant\'s is opening')

    


# In[146]:


aa = Restaurant('st','cc')


# In[147]:


#访问属性
aa.restaurant_name


# In[148]:


aa.cuisine_type


# In[149]:


#调用方法
aa.open_restaurant()


# In[150]:


aa.describe_restaurant()


# In[ ]:





# In[80]:


class Dog():
    """一次模拟小狗的简单尝试""" 
    def __init__(self,name,age): 
        """初始化属性name和age""" 
        self.name = name
        self.age = age
    def sit(self): 
        """模拟小狗被命令时蹲下""" 
        print(self.name.title() + " is now sitting.") 
    def roll_over(self):
        """模拟小狗被命令时打滚""" 
        print(self.name.title() + " rolled over!")


# In[81]:


my_dog = Dog('white',10)


# In[82]:


my_dog.name


# In[83]:


my_dog = Dog('willie', 6)
my_dog.sit()
my_dog.roll_over()


# In[ ]:





# In[8]:


def fib(max):
    a,b,n =0,1,0
    while n <max:
        print(b)
        a,b=b,a+b
        n=n+1


# In[9]:


fib(7)


# In[ ]:





# # if __name__ == '__main__':
# 知乎收藏
# https://mp.weixin.qq.com/s?__biz=MzU2ODYzNTkwMg==&mid=2247485702&idx=1&sn=9c6c86a977a0093d4474b1099fcf8b01&chksm=fc8bb197cbfc38814cc9308206e8fc2e8bf14eb6582aa20bf3eaf8627dabb176855035c734b6&token=750745785&lang=zh_CN##

# In[1]:


name = 'handsomeb'
print ('name',name)
def fun_A ():
    print('调用方法A')
if __name__ == '__main__':
    print('程序入口')
    fun_A()


# In[ ]:


name = 'handsomeb'
print ('name',name)
def fun_A ():
    print('调用方法A')

print('程序入口')
fun_A()


# In[ ]:


name = 'handsomeb'
print ('name',name)
def fun_A ():
    print('调用方法A')
def print_name():
    print ('__name__的值：',__name__)

print('程序入口')
fun_A()
print_name()


# In[ ]:





# # 编辑距离
# ---
# 链接：https://zhuanlan.zhihu.com/p/80682302

# In[58]:


# 计算最少的步数
def minDistance(s1, s2) ->int: # -> 表明了函数的返回值为int类型

    def dp(i, j):
        # base case
        if i == -1: return j + 1
        if j == -1: return i + 1
        if s1[i] == s2[j]:
            return dp(i - 1, j - 1)  # 啥都不做
        else:
            return min(
                dp(i, j - 1) + 1,    # 插入
                dp(i - 1, j) + 1,    # 删除
                dp(i - 1, j - 1) + 1 # 替换
            )

    # i，j 初始化指向最后一个索引 
    return dp(len(s1) - 1, len(s2) - 1)
   


# In[59]:


minDistance('rad','apple')


# def dp(i, j) -> int
# 
# 返回 s1[0..i] 和 s2[0..j] 的最小编辑距离

# In[60]:


'''
if s1[i] == s2[j]:
    return dp(i - 1, j - 1)  # 啥都不做
# 解释：
# 本来就相等，不需要任何操作
# s1[0..i] 和 s2[0..j] 的最小编辑距离等于
# s1[0..i-1] 和 s2[0..j-1] 的最小编辑距离
# 也就是说 dp(i, j) 等于 dp(i-1, j-1)


如果 s1[i]！=s2[j]，就要对三个操作递归了，稍微需要点思考：
# 插入
    dp(i, j - 1) + 1,    
# 解释：
# 我直接在 s1[i] 插入一个和 s2[j] 一样的字符
# 那么 s2[j] 就被匹配了，前移 j，继续跟 i 对比
# 别忘了操作数加一

# 删除
dp(i - 1, j) + 1,    
# 解释：
# 我直接把 s[i] 这个字符删掉
# 前移 i，继续跟 j 对比
# 操作数加一

'''


# In[61]:


def dp(a=2,b=3):
    return a,b


# In[62]:


dp()


# In[65]:


def minDistance(s1, s2) ->int: # -> 表明了函数的返回值为int类型

    def dp(i, j):
        i=1
        j=2

    return dp(s1 - 1, s2 - 1)


# In[67]:


minDistance(5,3)


# In[ ]:





# # 装饰器
# ---
# 廖雪峰
# https://www.liaoxuefeng.com/wiki/1016959663602400/1017451662295584

# In[69]:


import time, functools
def metric(fn):
    print('%s executed in %s ms' % (fn.__name__, 10.22))
    return fn
@metric
def fast(x, y):
    time.sleep(0.0012)
    return x + y;

@metric
def slow(x, y, z):
    time.sleep(0.1234)
    return x * y * z;

f = fast(11, 22)
s = slow(11, 22, 33)
if f != 33:
    print('测试失败!')
elif s != 7986:
    print('测试失败!')


# In[71]:


import functools

def log(func):
    @functools.wraps(func)
    def wrapper(*args, **kw):
        print('call %s():' % func.__name__)
        return func(*args, **kw)
    return wrapper


# In[75]:


log('test')


# In[ ]:





# In[2]:


def log(text):
    def decorator(func):
        @functools.wraps(func)
        def wrapper(*args, **kw):
            print('%s %s():' % (text, func.__name__))
            return func(*args, **kw)
        return wrapper
    return decorator


# In[ ]:





# In[4]:


def log(text):
    def decorator(func):
        def wrapper(*args, **kw):
            print('%s %s():' % (text, func.__name__))
            return func(*args, **kw)
        return wrapper
    return decorator


# In[5]:


@log('execute')
def now():
    print('2015-3-25')


# In[6]:


now()


# In[7]:





# In[8]:


now.__name__


# In[ ]:





# # python3在同一行内输入n个数并用列表保存的例子
# ---
# https://www.zhangshengrong.com/p/boNwrnPoaw/

# In[5]:


list1 = list(map(int,input().split()))


# In[22]:


n = input()
n = int(n)
list1 = []
list1 = input().split()
list2 = []
i = 0
while i < n:
  m = int(list1[i])
  list2.append(m)
  i += 1
print(list2)


# In[ ]:


x = input("请输入值，用空格分开")
xlist=x.split(" ")
print(xlist)


# In[ ]:





# In[3]:


state = (1,3)


# In[4]:


len (state)


# In[6]:


state = (1,5)
len (state)


# In[ ]:





# In[1]:


L = [1,0]
len(L)


# In[2]:


range(len(L))


# In[ ]:





# In[ ]:





# In[31]:



def triangles(n):           #定义一个函数,并定义一个参数n,现在讲n看做是需要的杨辉三角的层数
    L = [1]                 #定义一个列表L,并将其定义为是一个[1]的列表
    while len(L) < n:      #采用循环的方式,如果len(L)也就是层数,小于给定的层数,那么就可以继续循环
        yield L            #重点来了!记住此位置,下次循环直接从此开始!yeild是如此神奇
        L.append(0)       #现在生成一个新的列表, 就是在列表L后面加1
        L = [L[i - 1] + L[i] for i in range(len(L))]


# In[32]:


triangles(10)


# In[33]:





# In[ ]:





# 
# n = 0
# results = []
# for t in triangles(n):
#     results.append(t)
#     n = n + 1
#     if n == 10:
#         break
# 
# for t in results:
#     print(t)

# In[36]:


def triangles():           #定义一个函数,并定义一个参数n,现在讲n看做是需要的杨辉三角的层数
    L = [1]                 #定义一个列表L,并将其定义为是一个[1]的列表
    while len(L) < n:      #采用循环的方式,如果len(L)也就是层数,小于给定的层数,那么就可以继续循环
        yield L            #重点来了!记住此位置,下次循环直接从此开始!yeild是如此神奇
        L.append(0)       #现在生成一个新的列表, 就是在列表L后面加1
        L = [L[i - 1] + L[i] for i in range(len(L))]


# In[ ]:





# In[2]:


import matplotlib.pyplot as plt
import numpy as np


# In[3]:


x = np.linspace(0,10,30)
plt.plot(x,np.sin(x))
plt.plot(x,np.sin(x),'-o')


# In[6]:


rng = np.random.RandomState(0)
x = rng.randn(100)
y = rng.randn(100)
colors = rng.rand(100)
sizes = 1000 * rng.rand(100)

plt.scatter(x,y,c=colors,s=sizes,alpha=0.3,cmap='viridis')
plt.colorbar() #展示色阶

x = [1,2,3,4,5,6,7,8]
y = [3,1,4,5,8,9,7,2]
label = ['A','B','C','D','E','F','G','H']
plt.bar(x,y,tick_label = label)
data = np.random.randn(100)
plt.hist(data)
plt.hist(data,bins=30,histtype='stepfilled',density=True)
plt.show()


# In[6]:





# # 计数

# In[20]:


test_list = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'a', 'f', 's', 'b', 'h', 'k', 'i', 'j', 'c', 'd', 'f']


# ## 使用字典解决（dict）

# In[21]:


counter_dict = {}
for item in test_list:
    if item in counter_dict:
        counter_dict[item] += 1
    else:
        counter_dict[item] = 1
        
print (counter_dict)


# ## 使用dict.setdefault(key, dvalue)方法解决

# In[22]:


counter_sdic = {}
for item in test_list:
    counter_sdict[item] = counter_sdict.setdefault(item,0)
print (counter_sdict)


# ## 使用defaultdict类解决
# --使用defaultdict与使用dict的区别在于，defaultdict能够自动对获取结果进行排序

# In[23]:


from collections import defaultdict
counter_ddict = defaultdict(int)
for item in test_list:
    counter_ddict[item] += 1
print (counter_ddict)


# ## 使用set list count

# In[26]:


r_list = []
temp = set(test_list)
for item in temp:
    r_list.append((item,test_list.count(item)))
print (r_list)


# ## Counter()

# In[27]:


from collections import Counter
print (Counter(test_list))


# In[ ]:





# In[ ]:




